package com.yellow.cloud.security.oauth2.service;

import com.yellow.cloud.security.oauth2.client.SystemClient;
import com.yellowframework.cloud.domain.system.ext.SysUserExt;
import com.yellowframework.cloud.utils.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ClientDetailsService clientDetailsService;

    @Resource
    private SystemClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if(authentication==null){
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if(clientDetails!=null){
                //密码
                String clientSecret = clientDetails.getClientSecret();
                return new org.springframework.security.core.userdetails.User(username,clientSecret,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }

        if (StringUtils.isEmpty(username)) {
            return null;
        }

        //请求系统服务查询用户
        SysUserExt user = userClient.info(username);
        if(Objects.isNull(user)){
            // 返回NULL表示用户不存在，Spring Security会抛出异常
            return null;
        }

        //取出正确密码（hash值）
        String password = user.getPassword();

        // 权限code集合
        String userPermissionString  = StringUtils.join(user.getPermissions(), ",");

        User userDetails = new User(username, password, new HashSet<>(AuthorityUtils.commaSeparatedStringToAuthorityList(userPermissionString)));
        userDetails.setId(user.getId());
        // 用户名称
        userDetails.setName(user.getName());
        // 用户角色
        userDetails.setRoles(user.getRoleNames());
        return userDetails;
    }
}
